<template>
  <div class="view-fill">
    <div v-if="!showModify.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('measuringInstrument:update') &&
              formInfo.data.status === 0
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('measuringInstrument:submit') &&
              formInfo.data.status === 0
            "
            @click="submit"
            >提交
          </el-button>
          <el-button
            v-if="
              $permission('measuringInstrument:export') &&
              formInfo.data.status === 1
            "
            @click="exportExcel"
            >导出excel
          </el-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="
              $permission('measuringInstrument:printDetail') &&
              formInfo.data.status === 1
            "
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="formInfo"
              :image-field="formInfo.imageField"
            />
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>证照信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="licenseInfo"></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>上次检定信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="verificationInfo"></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>检定计划</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="verificationPlan"></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="计量器具检定记录"
                  name="first"
                  v-if="$permission('assetInstrumentsPlan:history')"
                >
                  <el-button :disabled="!canCreate" @click="create"
                    >新增
                  </el-button>
                  <!-- 表格 -->
                  <page-table
                    :refresh="instrumentsRecordTableInfo.refresh"
                    :init-curpage="instrumentsRecordTableInfo.initCurpage"
                    v-model:data="instrumentsRecordTableInfo.data"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :api="instrumentsRecordTableInfo.api"
                    :query="instrumentsRecordFilterInfo.query"
                    :field-list="instrumentsRecordTableInfo.fieldList"
                    :handle="instrumentsRecordTableInfo.handle"
                    @handleEvent="handleEvent"
                    :isDynamic="true"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfoDialog.ref"
        :disabled="formInfoDialog.disabled"
        :data="formInfoDialog.data"
        :field-list="formInfoDialog.fieldListRes"
        :rules="formInfoDialog.rules"
        :label-width="formInfoDialog.labelWidth"
      >
        <template v-slot:form-verificationDate>
          <el-date-picker
            v-model="formInfoDialog.data.verificationDate"
            value-format="YYYY-MM-DD"
          />
        </template>

        <template v-slot:form-filePathList>
          <UploadImg
            v-model:value="formInfoDialog.data.filePathList"
            :action="action"
            list-type="text"
            title="附件"
            :file-type="fileType"
            :response-fn="handleResponse"
          />
        </template>
      </PageForm>
    </page-dialog>
    <!-- 新增或修改 -->
    <equipment-archives-modify
      v-if="showModify.visible"
      :id="id"
      v-model:visible="showModify.visible"
      :title="showModify.title"
      :type="showModify.type"
      @returnModify="modifyCallback"
    />
  </div>
</template>

<script setup name="measuringInstrumentDetails">
import utils from '@/common/js/utils' // 公共方法
import axios from 'axios'
import EquipmentArchivesModify from './modify'
import {
  detailMeasuringInstrument,
  submitMeasuringInstrument,
  exportMeasuringInstrumentDetail,
} from '@/api/equipment.js'
import { getCustomizeSetting } from '@/api/customize'
import {
  getMeasuringVerificationRecordPageAll,
  createMeasuringVerificationRecord,
  updateMeasuringVerificationRecord,
  deleteMeasuringVerificationRecord,
  getMeasuringVerificationRecordById,
} from '@/api/quality'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
  },
})
const canCreate = computed(() => {
  return (
    formInfo.value.data.status == 1 && formInfo.value.data.enableStatus == 1
  )
})
const fileType = ref(['docx', 'pdf', 'doc'])
const activeName = ref('first')
const title = ref('计量器具详情')
const formInfo = ref({
  ref: null,
  data: {},
  imageField: {
    label: '计量器具照片',
    value: 'pictureList',
  },
  fieldList: [
    {
      label: '器具标准名称',
      value: 'commonName',
      type: 'text',
    },
    {
      label: '资产名称',
      value: 'assetName',
      type: 'text',
    },
    { label: '资产卡片号', value: 'assetCode', type: 'text' },
    { label: '器具编码', value: 'code', type: 'text' },
    {
      label: '专业分类',
      value: 'professionalClassificationValue',
      type: 'text',
    },
    {
      label: '是否强检',
      value: 'mandatoryTestValue',
      type: 'text',
    },
    {
      label: '拼音码',
      value: 'pinyinCode',
      type: 'text',
    },
    {
      label: '计量单位',
      value: 'unitName',
      type: 'text',
    },
    {
      label: '准确度',
      value: 'accuracy',
      type: 'text',
    },
    {
      label: '品牌',
      value: 'trademark',
      type: 'text',
    },
    {
      label: '规格',
      value: 'standard',
      type: 'text',
    },
    {
      label: '测量范围',
      value: 'measurementRange',
      type: 'text',
    },
    {
      label: '检定类型',
      value: 'verificationTypeValue',
      type: 'text',
    },
    {
      label: '主要参数',
      value: 'mainParameter',
      type: 'text',
    },
    {
      label: '出厂编号',
      value: 'factoryNo',
      type: 'text',
    },
    {
      label: '检定责任人',
      value: 'managerUserName',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'text',
    },
    /*  {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    }, */

    /*  {
      label: '检定周期(月)',
      value: 'verificationPeriod',
      type: 'text',
    },
  
    {
      label: '检定单位',
      value: 'verificationUnit',
      type: 'text',
    },
    {
      label: '上次检定日期',
      value: 'verificationDate',
      type: 'text',
    },
   
    {
      label: '下次检定日期',
      value: 'validityDate',
      type: 'text',
    },
    {
      label: '最新检定结果',
      value: 'verificationResultValue',
      type: 'text',
    },
    {
      label: '检定证书编号',
      value: 'verificationCertificateNumber',
      type: 'text',
    }, */
  ],
  labelWidth: '120px',
})
const verificationInfo = ref({
  fieldList: [
    {
      label: '上次检定日期',
      value: 'verificationDate',
      type: 'text',
    },
    {
      label: '上次检定结果',
      value: 'verificationResult',
      type: 'text',
    },
    {
      label: '上次检定证书编号',
      value: 'verificationCertificateNumber',
      type: 'text',
    },
    {
      label: '上次检定单位',
      value: 'verificationUnit',
      type: 'text',
    },
  ],
  labelWidth: '140px',
})
const verificationPlan = ref({
  fieldList: [
    {
      label: '检定周期(月)',
      value: 'verificationPeriod',
      type: 'text',
    },
    {
      label: '任务创建于：任务开始前',
      value: 'taskCreateEarlyDay',
      type: 'text',
    },
    {
      label: '任务提醒于：任务开始前',
      value: 'taskWarnEarlyTime',
      type: 'text',
    },
    {
      label: '下次检定日期',
      value: 'validityDate',
      type: 'text',
    },
  ],
})
const formInfoDialog = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '标准名称',
      value: 'commonName',
      type: 'input',
      disabled: true,
    },
    { label: '器具编码', value: 'code', type: 'input', disabled: true },
    {
      label: '是否强检',
      value: 'isMandatoryInspectionValue',
      type: 'select-model',
      code: 'yes_or_no',
      disabled: true,
    },
    {
      label: '资产名称',
      value: 'assetName',
      type: 'input',
      disabled: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      disabled: true,
    },
  ],
  fieldListRes: [
    {
      label: '检定日期',
      value: 'verificationDate',
      type: 'slot',
      placeholder: false,
    },
    {
      label: '证书编号',
      value: 'verificationCertificateNumber',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '检定类型',
      value: 'verificationType',
      type: 'select-model',
      code: 'verification_type',
      checkDefault: true,
    },
    {
      label: '检定结果',
      value: 'verificationResult',
      type: 'select-model',
      code: 'verification_result',
      checkDefault: true,
    },
    {
      label: '检定单位',
      value: 'verificationUnit',
      type: 'input',
      maxlength: 200,
    },
    {
      label: '上传附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    verificationDate: [
      { required: true, message: '请选择检定日期', trigger: 'change' },
    ],
    verificationCertificateNumber: [
      { required: true, message: '请输入证书编号', trigger: 'blur' },
    ],
    verificationUnit: [
      { required: true, message: '请输入检定单位', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const licenseInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '是否关联证照',
      value: 'needLicenseValue',
      type: 'text',
    },
    {
      label: '证号',
      value: 'licenseNumber',
      type: 'text',
    },
    {
      label: '证照名称',
      value: 'licenseName',
      type: 'text',
    },
    {
      label: '英文名称',
      value: 'enName',
      type: 'text',
    },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'text',
    },
    {
      label: '证照失效日期',
      value: 'licenseEndDate',
      type: 'text',
    },
    {
      label: '生产厂家',
      value: 'brandName',
      type: 'text',
    },
  ],
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '800px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 操作流水
const affairTableInfo = ref({
  query: {
    orderType: 50,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const instrumentsRecordTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: updateDetail,
        show: proxy.$permission('measuringInstrument:update'),
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('measuringInstrument:delete'),
      },
    ],
  },
})
const instrumentsRecordFilterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      measuringInstrumentId: {
        asTbName: 'measuring_verification_record',
        columnName: 'measuring_instrument_id',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: proxy.id,
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
})
const btnList = ref([])
const showModify = ref({
  title: '修改',
  type: 'update',
  visible: false,
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})
onMounted(() => {
  getDeatil()
  getInstrumentsRecordCustomize()
})
function handleResponse(response, file) {
  return file
}
function submit() {
  submitMeasuringInstrument([props.id]).then((resp) => {
    if (resp && resp.success) {
      modifyCallback()
    }
  })
}
//打印
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'measuringInstrumentDetail',
    deptId: props.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: props.id,
          },
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...instrumentsRecordFilterInfo.value.query,
            }),
          },
        })
      }
    }
  })
}
function printCallback() {}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: props.id,
    },
    callback: printCallback,
    data: {
      customParam: JSON.stringify({
        ...instrumentsRecordFilterInfo.value.query,
      }),
    },
  })
  popoverVisible.value = false
}
function exportExcel() {
  exportMeasuringInstrumentDetail(props.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  formInfoDialog.value.ref.validate((valid) => {
    if (valid) {
      let data = { ...formInfo.value.data, ...formInfoDialog.value.data }
      data['measuringInstrumentId'] = proxy.id
      let api = formInfoDialog.value.data.id
        ? updateMeasuringVerificationRecord
        : createMeasuringVerificationRecord
      api(data).then((resp) => {
        if (resp && resp.success) {
          formInfoDialog.value.ref.validateField()
          dialogInfo.value.visible = false
          dialogInfo.value.msg = ''
          getDeatil()
          getInstrumentsRecordCustomize()
        }
      })
    }
  })
}
function create() {
  formInfoDialog.value.data = {}
  dialogInfo.value.visible = true
}
function updateDetail(row) {
  getMeasuringVerificationRecordById(row.id).then((res) => {
    if (res.success) {
      dialogInfo.value.visible = true
      formInfoDialog.value.data = res.data
    }
  })
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  deleteMeasuringVerificationRecord(data).then((resp) => {
    if (resp && resp.success) {
      getDeatil()
      getInstrumentsRecordCustomize()
    }
  })
}
const returnBack = () => {
  emits('returnBack')
}
const getDeatil = () => {
  detailMeasuringInstrument(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.value.data = data
      formInfo.value.data['unitId'] = data.unitId == -2 ? '' : data.unitId
      formInfo.value.data['professionalClassification'] =
        data.professionalClassification == -2
          ? ''
          : data.professionalClassification
      formInfo.value.data.taskWarnEarlyTime =
        data.taskWarnEarlyTime < 0 ? '-' : data.taskWarnEarlyTime
      formInfo.value.data.taskCreateEarlyDay =
        data.taskCreateEarlyDay < 0 ? '-' : data.taskCreateEarlyDay
      licenseInfo.value.data = {
        needLicense: data.needLicense,
        needLicenseValue: data.needLicenseValue,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        enName: data.enName,
        licenseId: data.licenseId,
        brandId: data.brand,
      }
      verificationInfo.value.data = {
        verificationDate: data.verificationDate,
        verificationResult: data.verificationResultValue,
        verificationCertificateNumber: data.verificationCertificateNumber,
        verificationUnit: data.verificationUnit,
      }
      verificationPlan.value.data = {
        verificationPeriod: data.verificationPeriod,
        taskCreateEarlyDay: data.taskCreateEarlyDay + '天',
        taskWarnEarlyTime: data.taskWarnEarlyTime + data.taskWarnUnitValue,
        validityDate: data.validityDate,
      }
      if (formInfo.value.data.picture) {
        formInfo.value.data.pictureList = utils.splitArr(
          formInfo.value.data.picture
        )
      }
    }
  })
}

function update() {
  showModify.value.visible = true
}
const modifyCallback = () => {
  getDeatil()
  getInstrumentsRecordCustomize()
}
function handleClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
    getInstrumentsRecordCustomize()
  }
}
function getInstrumentsRecordCustomize() {
  let obj = {
    assetName: {
      label: '资产名称',
      value: 'assetName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    isMandatoryInspection: {
      label: '是否强检',
      value: 'isMandatoryInspection',
      componentType: 'select-model',
      code: 'yes_or_no',
      show: false,
      hidden: true,
    },
    useStatus: {
      label: '使用状态',
      value: 'useStatus',
      componentType: 'select-model',
      code: 'asset_font_status',
      show: false,
      hidden: true,
    },
    preVerificationDate: {
      label: '上次检定日期',
      value: 'preVerificationDate',
      componentType: 'date',
      show: false,
      hidden: true,
    },
    preVerificationPeriod: {
      label: '检定周期',
      value: 'preVerificationPeriod',
      componentType: 'number',
      show: true,
      hidden: true,
    },
    checkDatePlan: {
      label: '计划检定日期',
      value: 'checkDatePlan',
      componentType: 'date',
      show: false,
      hidden: true,
    },
  }
  instrumentsRecordTableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  instrumentsRecordFilterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  let param = {
    tableKey:
      'measuringVerificationRecordList-com.slip.spd.entity.vo.quality.MeasuringVerificationRecordVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      instrumentsRecordFilterInfo.value.query.customizeUserVO = data
      let tableFieldInfo = proxy.$fn.setFieldList(
        instrumentsRecordTableInfo.value.fieldList,
        data.detail,
        true
      )
      let searchInfo = proxy.$fn.setSearchList(
        instrumentsRecordFilterInfo.searchList,
        data.detail
      )
      instrumentsRecordTableInfo.value.fieldList = tableFieldInfo.fieldList
      instrumentsRecordFilterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...instrumentsRecordFilterInfo.value.query.queryMap,
      }

      instrumentsRecordFilterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        instrumentsRecordFilterInfo.value.query.queryMap
      )
      instrumentsRecordTableInfo.value.api =
        getMeasuringVerificationRecordPageAll
      instrumentsRecordTableInfo.value = instrumentsRecordTableInfo.value
      instrumentsRecordFilterInfo.value = instrumentsRecordFilterInfo.value
      getInstrumentsRecordList()
    }
  })
}
function getInstrumentsRecordList() {
  instrumentsRecordTableInfo.value.refresh = Math.random()
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
:deep(.el-upload-list) {
  margin-top: 0;
}
</style>
